import React, { Component } from 'react'
import { HeaderBar, FooterBar, CartList, Toast, TotalPrice } from '../../components'
import '../../mock'
import cartStyle from './cart.module.scss'
import axios from 'axios'

/***
 * 基本数据类型 / 引用类型
 * 
 * 
 * 基本数据类型-按值-传递 / 引用数据类型按-引用-传递
 * 
 * 
 *
 * 0101010101
 * 
 * 栈         堆
 * let arr  ｜= []
 * 
 *  基本 ---- 引用

 * let brr = []
 * 
 * 浅拷贝 （赋值拷贝）
 *
 * let a = 1
 *
 * 深拷贝
 *
 */
// [...this.state.list]

let state = {
  count: 0,
  list: [],
}

// let a = 1
// let arr = []
// let brr = JSON.parse(JSON.stringify(arr))
// let b = a

export default class Cart extends Component {
  state = {
    // 只读
    showToast: true,
    list: [],
    totalPrice: 0,
    allChecked: false,
  }

  // 请求数据
  async fetchCartData() {
    const response = await axios.get('/api/list')
    this.setState({
      list: response.data.data,
    })
  }

  // 调用数据
  componentDidMount() {
    this.fetchCartData()
  }

  // 减少商品函数
  handleReduceItem(id) {
    const { list } = this.state
    let goods = list.find((v) => v.id === id)
    if (goods.number <= 1) {
      if (window.confirm('确认删除吗?')) {
        // 删除 调用：splice
        let copyList = [...this.state.list]
        copyList.splice(
          copyList.findIndex((v) => v.id === id),
          1
        )
        // 删除数据后，判断全选
        let allChecked = copyList.every((item) => {
          return item.isSelected
        })
        this.setState({ list: copyList, allChecked })
      }
      return
    }
    goods.number--
    // 手动更新 调用render方法渲染页面
    this.setState({}) // render方法
    console.log('goods:', goods)
  }

  // ++
  handleAddItem(id) {
    const { list } = this.state
    let goods = list.find((v) => v.id === id)
    goods.number++
    /**
     *     let arr = [1, 2, 3]
     * arr.splice()
     * 引用类型 arr {} fun
     * 栈             堆
     *
     * arr 指针 ---  [1,2,3]
     *  --新指针             {}
     * diff
     * 旧dom 新dom
     * ()
     *
     * ({})
     */
    this.setState({}) // {}
  }

  // 反选函数
  handleSelected = ({ id, checked }) => {
    this.state.list.forEach((item) => {
      if (item.id === id) {
        item.isSelected = checked
      }
    })
    // 根据每一个选中的项，去判断，总的选中项
    const allChecked = this.state.list.every((item) => {
      return item.isSelected
    })
    // 重新渲染
    this.setState({ allChecked })
  }

  // 总选
  handleAllChecked = (e) => {
    // 异步更新
    // 1. 首先更新本身的选中
    this.setState({ allChecked: e.target.checked }, () => {
      // setState的第二个参数，获取异步更新之后的值
      this.state.list.forEach((item) => {
        item.isSelected = this.state.allChecked
      })
      this.setState({})
    })
  }

  // 计算总价
  getTotalPrice = () => {
    // reduce 第一个参数是一个回调函数，此回调函数的第一个参数，等于reduce的第二个参数
    return this.state.list.reduce((num, item) => {
      // 选中才计算
      if (item.isSelected) {
        return num + item.price.toFixed(2) * 1000 * item.number
      } else {
        return num
      }
    }, 0)
  }

  // 提取提示框的公共代码
  handleToastisShow = () => {
    return (
      <>
        {this.state.showToast ? (
          <Toast
            handleCloseToast={(index) => {
              this.setState({
                showToast: false,
              })
            }}
          ></Toast>
        ) : null}
      </>
    )
  }

  render() {
    const { list, allChecked } = this.state
    return (
      <div className={cartStyle['cart-container']}>
        {/* 全选 */}
        <input type="checkbox" checked={allChecked} onChange={(e) => this.handleAllChecked(e)} />
        {/* 弹出框控制 */}
        {this.handleToastisShow()}

        <header className={cartStyle['cart-header']}>
          <HeaderBar />
          <TotalPrice totalPrice={this.getTotalPrice() / 1000} />
        </header>
        <main className={cartStyle['cart-main']}>
          {list.map((item, i) => {
            return (
              <CartList
                key={item.id}
                item={item}
                handleSelected={({ id, checked }) => this.handleSelected({ id, checked })}
                handleAddItem={(id) => this.handleAddItem(id)}
                handleReduceItem={(id) => this.handleReduceItem(id)}
              />
            )
          })}
        </main>
        <footer className={cartStyle['cart-footer']}>
          <FooterBar></FooterBar>
        </footer>
      </div>
    )
  }
}
